// ignore_for_file: depend_on_referenced_packages

import 'dart:async';
import 'dart:isolate';

import 'package:fast_build/common/theme/theme.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:hk_base/hk_base.dart';
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_ume/flutter_ume.dart'; // UME 框架
import 'package:flutter_ume_kit_console/flutter_ume_kit_console.dart'; // debugPrint 插件包
import 'package:flutter_ume_kit_device/flutter_ume_kit_device.dart'; // 设备信息插件包
import 'package:flutter_ume_kit_perf/flutter_ume_kit_perf.dart'; // 性能插件包
import 'package:flutter_ume_kit_show_code/flutter_ume_kit_show_code.dart'; // 代码查看插件包
import 'package:flutter_ume_kit_ui/flutter_ume_kit_ui.dart'; // UI 插件包
import 'package:flutter_ume_kit_dio/flutter_ume_kit_dio.dart'; // Dio 网络请求调试工具

import 'dio/dio_util.dart';
import 'route/app_router_service.dart';
import 'route/app_routes.dart';
import 'route/not_found_page.dart';

void main() {
  FlutterError.onError = (FlutterErrorDetails details) async {
    // 线上环境，走上报逻辑
    if (kReleaseMode) {
      // _customerReport(details.exception, details.stack);
      Zone.current.handleUncaughtError(
          details.exception, details.stack ?? StackTrace.fromString("empty"));
    } else {
      // _customerReport(details.exception, details.stack);
      // 开发期间，走Console抛出
      FlutterError.dumpErrorToConsole(details);
    }
  };

  // TODO:②TAG2 isolate 处理
  Isolate.current.addErrorListener(
    RawReceivePort((dynamic pair) async {
      final isolateError = pair as List<dynamic>;
      _customerReport(isolateError, StackTrace.fromString("empty"));
    }).sendPort,
  );

  bool showDebugTool = true;
  //TODO:③ Dart异常捕获
  runZonedGuarded(() {
    _initBeforeRunApp().then((value) {
      if (showDebugTool == false) {
        HkLog.init(tag: "正式环境LogUtil", isDebug: false, maxLen: 800);
        runApp(RootPage());
      } else {
        HkLog.init(tag: "测试环境LogUtil", isDebug: true, maxLen: 800);
        PluginManager.instance
          ..register(const WidgetInfoInspector())
          ..register(const WidgetDetailInspector())
          ..register(const ColorSucker())
          ..register(AlignRuler())
          ..register(const ColorPicker()) // 新插件
          ..register(const TouchIndicator()) // 新插件
          ..register(Performance())
          ..register(const ShowCode())
          ..register(const MemoryInfoPage())
          ..register(CpuInfoPage())
          ..register(const DeviceInfoPanel())
          ..register(Console())
          ..register(DioInspector(dio: DioUtil().dio));
        // flutter_ume 0.3.0 版本之后
        runApp(UMEWidget(enable: true, child: RootPage())); // 初始化
      }
      _otherConfig();
    });
  }, (exception, stackTrace) async {
    _customerReport(exception, stackTrace);
  });
}

// 其他插件初始化
void _otherConfig() {
  // EasyLoading 配置
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.circle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..maskColor = Colors.black.withOpacity(0.5)
    ..userInteractions = false
    ..dismissOnTap = false;
  // 设置安卓沉浸式状态栏
  if (!kIsWeb) {
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        systemNavigationBarDividerColor: Colors.transparent,
        // systemNavigationBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.dark);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
  // 强制竖屏
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
}

class RootPage extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return HkInit(builder: (context, child) {
      return GetMaterialApp(
        title: "快速构建",
        debugShowCheckedModeBanner: false,
        debugShowMaterialGrid: false,
        //debug模式隐藏Material标识
        defaultTransition: Get.defaultTransition,
        opaqueRoute: Get.isOpaqueRouteDefault,
        popGesture: Get.isPopGestureEnable,
        transitionDuration: Get.defaultTransitionDuration,
        // 是否打开性能测试层
        showPerformanceOverlay: false,
        darkTheme: DarkThemeStyle(),
        themeMode: ThemeMode.light,
        theme: LightThemeStyle(),
        getPages: AppPages.pages,
        initialRoute: AppPages.initial,
        // 监听路由打印
        navigatorObservers: [GetObserver(), AppRouterObserver()],
        builder: EasyLoading.init(builder: (context, widget) {
          return MediaQuery(
            //设置文字大小不随系统设置改变
            data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
            child: GestureDetector(
              onTap: () {
                FocusScopeNode currentFocus = FocusScope.of(context);
                if (!currentFocus.hasPrimaryFocus &&
                    currentFocus.focusedChild != null) {
                  FocusManager.instance.primaryFocus?.unfocus();
                }
              },
              child: widget,
            ),
          );
        }),
        // 设置未知路由的处理
        unknownRoute:
            GetPage(name: '/not-found', page: () => const NotFoundPage()),
        onUnknownRoute: (settings) {
          String name = settings?.name ?? "";
          print("未匹配到路由:$name");
          return GetPageRoute(
            page: () => const NotFoundPage(),
          );
        },
      );
    });
  }
}

/// 在启动之前要做的异步任务
Future<bool> _initBeforeRunApp() async {
  //runApp前调用，初始化绑定，手势、渲染、服务等
  WidgetsFlutterBinding.ensureInitialized();
  // sp初始化
  await HkCache.preInit();

  return true;
}

/// 自定义异常上报逻辑
void _customerReport(Object exception, StackTrace? stack) {
  HkLog.d("kReleaseMode:$kReleaseMode"); //false | true
  String tag = kReleaseMode == true ? "RELEASE" : "DEV" + "_CONSOLE";
  StackTrace trace = stack ?? StackTrace.fromString("empty");
  HkLog.d("$tag>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Exception:\n$exception");
  HkLog.d("$tag>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Stack:\n$trace");
}
